﻿using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Service;

namespace Missbot.AIModule.Gaming.SegmentAttach
{
    public class SegmentRecord : DbBaseEntity
    {
        public string UserID { get; init; }

        public string Segment { get; set; }

        public bool IsRare { get; set; }

        public Dictionary<string, int> TreasureRecord { get; } = new();

        public int FinalTreasureCount { get; set; }
    }

    public static class SegmentRecordDA
    {
        public static bool CanOpenFinalTreasure(this SegmentRecord entity)
        {
            if (entity.TreasureRecord.Count < AutofacSvc.Resolve<SegmentSvc>().Treasures.Count)
            {
                return false;
            }

            var totalCanOpenCount = entity.TreasureRecord.Values.Min();
            return totalCanOpenCount > entity.FinalTreasureCount;
        }

        public static SegmentRecord Get(string UserID)
        {
            var record = MongoService<SegmentRecord>.GetOnly(p => p.UserID == UserID);
            if (record != null)
            {
                return record;
            }

            record = new SegmentRecord { UserID = UserID };
            MongoService<SegmentRecord>.Insert(record);
            return record;
        }

        public static void ClearSegment(this SegmentRecord entity)
        {
            entity.Segment = null;
            entity.IsRare = false;
        }

        public static void AddTreasureRecord(this SegmentRecord entity, string treasure)
        {
            if (!entity.TreasureRecord.ContainsKey(treasure))
            {
                entity.TreasureRecord.Add(treasure, 0);
            }

            entity.TreasureRecord[treasure]++;
        }

        public static void Update(this SegmentRecord entity)
        {
            MongoService<SegmentRecord>.Update(entity);
        }
    }
}